package com.syni.mdd.yhd.common.all.service;

import com.alibaba.fastjson.JSON;
import com.qcloud.vod.VodUploadClient;
import com.qcloud.vod.model.VodUploadRequest;
import com.qcloud.vod.model.VodUploadResponse;
import com.syni.mdd.sjb.common.component.utils.common.utils.AppConfig;
import com.syni.mdd.sjb.common.component.utils.common.utils.ParamsMap;
import com.syni.mdd.sjb.common.component.utils.common.utils.ResultMapHelper;
import com.syni.mdd.sjb.common.component.utils.common.utils.SpringUtils;
import com.syni.mdd.sjb.common.component.utils.feign.dto.mdd.sjb.common.dxshapp.CommonPushToDsxhAppDto;
import com.syni.mdd.sjb.common.component.utils.feign.service.mdd.sjb.common.datatreasure.DxshApiNewsRestService;
import com.syni.mdd.sjb.common.component.utils.redis.utils.RedisTemplateUtils;
import com.syni.mdd.yhd.common.all.config.AuroraConfig;
import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.constants.ResultCode;
import com.syni.mdd.yhd.common.all.constants.ResultMsg;
import com.syni.mdd.yhd.common.all.entity.BmsDxNews;
import com.syni.mdd.yhd.common.all.entity.bo.common.MddDxshAppNewAdapterBo;
import com.syni.mdd.yhd.common.all.entity.cdn.BmsCdnData;
import com.syni.mdd.yhd.common.all.entity.user.BmsUser;
import com.syni.mdd.yhd.common.all.utils.*;
import com.syni.mdd.yhd.common.all.utils.aurora.AuroraPushUtils;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @className BmsUserOperationLogService
 * @description TOO
 * @Author cfx
 * @DATE 2019/4/9 12:04
 * @VERSION 1.0
 **/
@Service
@RefreshScope
@Data
public class BmsCommonService implements ApplicationContextAware {

    @Value("${API.AUTH:1}")
    private String API_AUTH;

    private final static Logger log = LoggerFactory.getLogger(BmsCommonService.class);
    public static String RUN_DEV = "dev";
    public static String RUN_PRO = "pro";

    public static Map<Integer,Integer> clientMap = new HashMap<>();
    public static Map<String,Integer> imgTypeMap = new HashMap();

    static {
        clientMap.put(Constants.WECHAT_CLIENT,Constants.WECHAT_CLIENT);
        clientMap.put(Constants.ANDROID_CLIENT,Constants.APP_CLIENT);
        clientMap.put(Constants.IOS_CLIENT,Constants.APP_CLIENT);

        imgTypeMap.put("image/jpeg",Constants.COMMON_FLAG_TRUE_INT);
        imgTypeMap.put("image/png",Constants.COMMON_FLAG_TRUE_INT);
        imgTypeMap.put("image/jpg",Constants.COMMON_FLAG_TRUE_INT);
    }
    private static ApplicationContext applicationContext;

    @Autowired
    BmsUserService bmsUserService;

    @Autowired
    BmsVideoService bmsVideoService;

    @Autowired
    BmsDxCommentService bmsDxCommentService;

    @Autowired
    BmsDxNewsService bmsDxNewsService;

    @Value("${app.h5.page}")
    private String publicityPage;

    private String secretId;

    private String secretKey;

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static String getActiveProfile(){
        if(applicationContext != null) {
            String[] profiles = applicationContext.getEnvironment().getActiveProfiles();
            if (profiles.length > 0) {
                return applicationContext.getEnvironment().getActiveProfiles()[0];
            }
        }
        return null;
    }

    public static boolean checkRunProfile(String profile){
        String nowProfile = getActiveProfile();
        if(profile != null){
            return profile.equals(nowProfile);
        }
        return true;
    }

    public Map<String,Object> getUploadVideoSign(){
        Signature sign = new Signature();
        sign.setSecretId(AppConfig.getProperty("cloud.secret.id"));
        sign.setSecretKey(AppConfig.getProperty("cloud.secret.key"));
        long time = System.currentTimeMillis() / 1000;
        int random = new Random().nextInt(java.lang.Integer.MAX_VALUE);
        int signValidDuration = 3600 * 24 * 2;
        //long expireTime = time + signValidDuration;
        sign.setCurrentTime(time);
        sign.setRandom(random);
        sign.setSignValidDuration(signValidDuration);

        //System.out.println("currentTime：" + time);
        //System.out.println("random：" + random);
        //System.out.println("expireTime：" + expireTime);
        try {
            String signature = sign.getUploadSignature();
            //System.out.println("signature : " + signature);
            return ResultMapHelper.success(signature,"获取签名成功！");
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return ResultMapHelper.failure("获取签名失败！");
        }
    }


    public Map<String, Object> uploadVideoFile(MultipartFile uploadFile) {
        if(uploadFile.isEmpty()){
            return ResultMapHelper.failure("请上传相关视频");
        }
        String uploadUrl = Upload.uploadVideo(uploadFile);
        System.out.println(uploadUrl);
        if("".equals(uploadUrl)){
            return ResultMapHelper.failure("上传失败");
        }
        Map<String,Object> resultMap = new HashMap<>();
        final Logger log = LoggerFactory.getLogger(getClass());
        VodUploadClient client = new VodUploadClient(AppConfig.getProperty("cloud.secret.id"),
                AppConfig.getProperty("cloud.secret.key"));
        VodUploadRequest request = new VodUploadRequest();
        request.setMediaFilePath(uploadUrl);
        try {
            VodUploadResponse response = client.upload("ap-guangzhou", request);
            log.info("Upload FileId = {}", response.getFileId());
            log.info("Upload MediaUrl = {}", response.getMediaUrl());
            //删除文件
            File file = new File(uploadUrl);
            if(file.exists()){
                file.delete();
            }
            resultMap.put("fileId",response.getFileId());
            resultMap.put("fileUrl",response.getMediaUrl());
            return ResultMapHelper.success(resultMap,"上传成功");
        } catch (Exception e) {
            // 业务方进行异常处理
            log.error("Upload Err", e);
            return ResultMapHelper.failure("上传失败");
        }
    }

    public Map<String, Object> checkPhoneRegister(String phone) {
        BmsUser bmsUser = bmsUserService.getBaseDao().findByPhone(phone);
        //检测手机号是否存在
        if(bmsUser == null){
            return ResultMapHelper.result(ResultCode.CODE_USER_PHONE_NO_EXIST,"手机号不存在");
        }
        //检测该手机号账户是否设置密码
        if(bmsUser.getIsSetPwd() == null || bmsUser.getIsSetPwd() == Constants.COMMON_FLAG_FALSE_INT){
            return ResultMapHelper.result(ResultCode.CODE_USER_NO_SET_PWD,"手机号无设置密码");
        }
        return ResultMapHelper.success("手机号存在，可以使用密码登录");
    }

    public Map<String,Object> uploadMoreImgFile(MultipartFile[] uploadFile,Integer fileType){
        //记录本地
        List<String> imgFileList = new LinkedList<>();
        //记录上传云的图片(用来删除)
        List<String> imgToCloud = new LinkedList<>();
        List<String> imgResultList = new LinkedList<>();
        if(uploadFile.length > 0){
            for(MultipartFile multipartFile : uploadFile){
                if(multipartFile.isEmpty()){
                    return ResultMapHelper.failure("请上传相关图片文件");
                }
                if(!imgTypeMap.containsKey(multipartFile.getContentType())){
                    //清空之前上传的文件
                    return ResultMapHelper.failure("上传图片格式错误");
                }
            }
            for(MultipartFile multipartFile : uploadFile){
                String uploadUrl = Upload.uploadImgFile(multipartFile,fileType);
                if("".equals(uploadUrl)){
                    deleteWasteFile(imgFileList);
                    deleteCloudFile(imgToCloud);
                    return ResultMapHelper.failure("文件上传失败");
                }
                imgFileList.add(uploadUrl);
                //上传到cdn文件服务器
                BmsCdnData bmsCdnData = this.uploadToCdn(CDNUtils.bucketName,"/business/",uploadUrl);
                if(bmsCdnData == null){
                    deleteWasteFile(imgFileList);
                    deleteCloudFile(imgToCloud);
                    return ResultMapHelper.failure("文件上传失败");
                }
                imgResultList.add(bmsCdnData.getSourceUrlBig());
                //记录上传过的图片
                String[] bigUrls = bmsCdnData.getSourceUrlBig().split("/");
                String bigUrl = bigUrls[bigUrls.length - 1];
                imgToCloud.add(bigUrl);
                if(StringUtils.isNotBlank(bmsCdnData.getSourceUrlSmall())) {
                    String[] smallUrls = bmsCdnData.getSourceUrlSmall().split("/");
                    String smallUrl = smallUrls[smallUrls.length - 1];
                    imgToCloud.add(smallUrl);
                    String[] uploadRescover = uploadUrl.split("/");
                    List<String> rescover = new ArrayList<>();
                    for(int ii=0;ii< uploadRescover.length - 1;ii++){
                        rescover.add(uploadRescover[ii]);
                    }
                    imgFileList.add(StringUtils.join(rescover,"/") + "/" + smallUrl);
                }
            }
            if(imgFileList.size() > 0){
                deleteWasteFile(imgFileList);
                return ResultMapHelper.success(imgResultList,"上传成功！");
            }
        }
        return ResultMapHelper.failure("请选择图片上传");
    }

    public Map<String,Object> uploadMoreImgFile_v2(MultipartFile[] uploadFile,Integer fileType){
        //记录本地
        List<String> imgFileList = new LinkedList<>();
        //记录上传云的图片(用来删除)
        List<String> imgToCloud = new LinkedList<>();
        List<String> imgResultList = new LinkedList<>();
        if(uploadFile.length > 0){
            for(MultipartFile multipartFile : uploadFile){
                if(multipartFile.isEmpty()){
                    return ResultMapHelper.failure("请上传相关图片文件");
                }
                if(!imgTypeMap.containsKey(multipartFile.getContentType())){
                    //清空之前上传的文件
                    return ResultMapHelper.failure("上传图片格式错误");
                }
            }
            for(MultipartFile multipartFile : uploadFile){
                String uploadUrl = Upload.uploadImgFile(multipartFile,fileType);
                if("".equals(uploadUrl)){
                    deleteWasteFile(imgFileList);
                    deleteCloudFile(imgToCloud);
                    return ResultMapHelper.failure("文件上传失败");
                }
                imgFileList.add(uploadUrl);
                //上传到cdn文件服务器
                BmsCdnData bmsCdnData = this.uploadToCdn(CDNUtils.bucketName,"/business/",uploadUrl);
                if(bmsCdnData == null){
                    deleteWasteFile(imgFileList);
                    deleteCloudFile(imgToCloud);
                    return ResultMapHelper.failure("文件上传失败");
                }
                //去除地址前缀
                try {
                    URL url = new URL(bmsCdnData.getSourceUrlBig());
                    String sourceUrlBig =  url.getPath();
                    imgResultList.add(sourceUrlBig);
                } catch (MalformedURLException e) {
                   log.error(e.getMessage());
                    imgResultList.add(bmsCdnData.getSourceUrlBig());
                }

                //记录上传过的图片
                String[] bigUrls = bmsCdnData.getSourceUrlBig().split("/");
                String bigUrl = bigUrls[bigUrls.length - 1];
                imgToCloud.add(bigUrl);
                if(StringUtils.isNotBlank(bmsCdnData.getSourceUrlSmall())) {
                    String[] smallUrls = bmsCdnData.getSourceUrlSmall().split("/");
                    String smallUrl = smallUrls[smallUrls.length - 1];
                    imgToCloud.add(smallUrl);
                    String[] uploadRescover = uploadUrl.split("/");
                    List<String> rescover = new ArrayList<>();
                    for(int ii=0;ii< uploadRescover.length - 1;ii++){
                        rescover.add(uploadRescover[ii]);
                    }
                    imgFileList.add(StringUtils.join(rescover,"/") + "/" + smallUrl);
                }
            }
            if(imgFileList.size() > 0){
                deleteWasteFile(imgFileList);
                return ResultMapHelper.success(imgResultList,"上传成功！");
            }
        }
        return ResultMapHelper.failure("请选择图片上传");
    }

    public void deleteWasteFile(List<String> fileUrls){
        if(fileUrls != null && fileUrls.size() > 0){
            for(String fileUrl : fileUrls){
                String s = Upload.getUploadBusinessAddress() + "/" + fileUrl;
                System.out.println(s);
                File file = new File(Upload.getUploadBusinessAddress() + "/" + fileUrl);
                if(file.exists()){
                    file.delete();
                }
            }
        }
    }

    public void deleteCloudFile(List<String> fileUrls){
        if(fileUrls != null && fileUrls.size() > 0){
            for(String imgUrl : fileUrls){
                CDNUtils.deleteCOS(CDNUtils.bucketName,"/business/" + imgUrl);
            }
        }
    }

    public Map<String, Object> uploadImgFile(MultipartFile uploadFile,Integer fileType) {
        if(uploadFile.isEmpty()){
            return ResultMapHelper.failure("请上传相关图片文件！");
        }
        if(!("image/jpeg".equals(uploadFile.getContentType()) || "image/png".equals(uploadFile.getContentType()))){
            return ResultMapHelper.failure("上传图片格式错误！");
        }
        //System.out.println(uploadFile.getContentType());
        String uploadUrl = Upload.uploadImgFile(uploadFile,fileType);
        //System.out.println(uploadUrl);
        if("".equals(uploadUrl)){
            return ResultMapHelper.failure("上传失败！");
        }
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("uploadImgUrl",uploadUrl);
        return ResultMapHelper.success(resultMap,"上传成功！");
    }

    public BmsCdnData uploadToCdn(String bucketName,String tip,String localPath){
        localPath =  Upload.getUploadBusinessAddress() + "/" + localPath;
        BmsCdnData bmsCdnData = CDNUtils.uploadCOS(bucketName,tip,localPath,CDNUtils.width,CDNUtils.height);
        System.out.println("数据：" + JSON.toJSONString(bmsCdnData));
        //BmsCdnData bmsCdnData = new BmsCdnData();
        //bmsCdnData.setSourceUrlBig("http://dsp-1253327941.cos.ap-guangzhou.myqcloud.com/business/b2019070314591845572L1.png");
        //bmsCdnData.setSourceUrlSmall("http://dsp-1253327941.cos.ap-guangzhou.myqcloud.com/business/s2019070314591845572L1.png");
        return bmsCdnData;
    }

    public BmsCdnData uploadToCdnByEnhance(String bucketName,String tip,String localPath){
        localPath =  Upload.getUploadBusinessAddress() + "/" + localPath;
        BmsCdnData bmsCdnData = CDNUtils.uploadCOS(bucketName,tip,localPath,0.5d);
        System.out.println("数据：" + JSON.toJSONString(bmsCdnData));
        //BmsCdnData bmsCdnData = new BmsCdnData();
        //bmsCdnData.setSourceUrlBig("http://dsp-1253327941.cos.ap-guangzhou.myqcloud.com/business/b2019070314591845572L1.png");
        //bmsCdnData.setSourceUrlSmall("http://dsp-1253327941.cos.ap-guangzhou.myqcloud.com/business/s2019070314591845572L1.png");
        return bmsCdnData;
    }

    /**
     * @Description 极光推送（消息类型）
     * @Param BmsDxNews
     * @Param pushCode
     * @Param desc
     * @Author: cfx
     * @Date: 2019/8/13
     */
    public static void pushToFront(BmsDxNews bmsDxNews,String pushCode,String alert){
        //使用极光推送推送至前端
        String userAlias;
        if(bmsDxNews.getOriginRole() == Constants.BUSINESS_ROLE_ID){
            userAlias = AuroraConfig.BUSINESS_PREFIX + bmsDxNews.getBmsBusinessId().toString();
        }else if(bmsDxNews.getOriginRole() == Constants.ASSISTANT_ROLE_ID){
            userAlias = AuroraConfig.BUSINESS_ASS_PREFIX + bmsDxNews.getBmsUserId().toString();
        }else {
            userAlias = AuroraConfig.USER_PREFIX + bmsDxNews.getBmsUserId().toString();
        }
        String[] audAlias = {userAlias};
        pushToFront(bmsDxNews,pushCode,alert,new HashMap<>(),audAlias);
    }

    public static void pushCustomMessageToFront(Map<String,String> messageBody,String[] userAlias,Integer application){
        AuroraPushUtils.sendCustomMessageToAppByAlias(AuroraPushUtils.ALL,userAlias,messageBody,application);
    }



    public static void pushToAssistant(BmsDxNews bmsDxNews,String pushCode,String alert){
        //判断这条消息是不是由店员引起的
        if(bmsDxNews.getParentType() == Constants.PARENTTYPT_SYS
                && bmsDxNews.getChildType() == Constants.PARENTTYPT_SYS_ASS_REA_INFORM_BUS){
            return;
        }
        if(bmsDxNews.getParentType() == Constants.PARENTTYPT_CON){
            return;
        }
        //给店员推送一条消息
        if(bmsDxNews.getParentType() == Constants.PARENTTYPT_INT
                && bmsDxNews.getChildType() == Constants.PARENTTYPT_INT_LIKE){
            BmsDxNewsService bmsDxNewsService = (BmsDxNewsService) SpringUtils.getBean("bmsDxNewsService");
            Map<String,Object> conditionMap = new HashMap();
            conditionMap.put("bmsVideoId",bmsDxNews.getBmsVideoId());
            conditionMap.put("parentType",BmsDxNewsService.PARENTTYPT_INT);
            conditionMap.put("childType",BmsDxNewsService.PARENTTYPT_INT_LIKE);
            conditionMap.put("originRole",Constants.ASSISTANT_ROLE_ID);
            List<BmsDxNews> bs = bmsDxNewsService.getBaseDao().findAll(new SpecificationUtils(conditionMap));
            if(bs != null && bs.size() > 0){
                bmsDxNews.setId(bmsDxNews.getId());
            }
        }else {
            bmsDxNews.setId(null);
        }
        bmsDxNews.setOriginRole(Constants.ASSISTANT_ROLE_ID);
        pushToFront(bmsDxNews,pushCode,alert);
    }

    public static void pushToFront(BmsDxNews bmsDxNews,String pushCode,String alert,String[] userAlias){
        //使用极光推送推送至前端
        pushToFront(bmsDxNews,pushCode,alert,new HashMap<>(),userAlias);
    }

    /**
     * @Description 极光推送（消息类型）
     * @Author: cfx
     * @Date: 2019/8/13
     */
    public static void pushToFront(BmsDxNews bmsDxNews,String pushCode,
                                   Map<String,Object> userData,String alert){
        //使用极光推送推送至前端
        String userAlias;
        if(bmsDxNews.getOriginRole() == Constants.BUSINESS_ROLE_ID){
            userAlias = AuroraConfig.BUSINESS_PREFIX + bmsDxNews.getBmsBusinessId().toString();
        }else if(bmsDxNews.getOriginRole() == Constants.ASSISTANT_ROLE_ID){
            userAlias = AuroraConfig.BUSINESS_ASS_PREFIX + bmsDxNews.getBmsBusinessId().toString();
        }else {
            userAlias = AuroraConfig.USER_PREFIX + bmsDxNews.getBmsUserId().toString();
        }
        String[] audAlias = {userAlias};
        pushToFront(bmsDxNews,pushCode,alert,new HashMap<>(),audAlias);
    }

    /**
     * @Description 极光推送（消息类型）
     * @Author: cfx
     * @Date: 2019/8/13
     */
    public static void pushToFront(BmsDxNews bmsDxNews,String pushCode,String alert,
                                   Map<String,Object> userData,String[] userAlias){
        AuroraPushUtils.sendMessageToAppByAlias(AuroraPushUtils.ALL,userAlias, pushCode,bmsDxNews,
                alert,userData,bmsDxNews.getOriginRole());
        if(bmsDxNews.getOriginRole() == Constants.BUSINESS_ROLE_ID){
            //商户端消息推送到电享生活app
            //查询该店铺的认领者
            BmsUserBusinessAuthService bmsUserBusinessAuthService = SpringUtils.getBean(BmsUserBusinessAuthService.class);

            Integer userId = bmsUserBusinessAuthService.findBusinessManager(bmsDxNews.getBmsBusinessId());
            if(userId == null){
                return;
            }
            DxshApiNewsRestService dxshApiNewsRestService =  SpringUtils.getBean(DxshApiNewsRestService.class);
            BmsBusinessService bmsBusinessService = SpringUtils.getBean(BmsBusinessService.class);
            if(dxshApiNewsRestService != null){
                CommonPushToDsxhAppDto commonPushToDsxhAppDto = new CommonPushToDsxhAppDto();
                commonPushToDsxhAppDto.setAlert(alert);
                commonPushToDsxhAppDto.setCode(pushCode);
                commonPushToDsxhAppDto.setRoleId(Constants.DXSH_ROLE_ID);
                commonPushToDsxhAppDto.setUserId(userId);
                commonPushToDsxhAppDto.setBusinessId(bmsDxNews.getBmsBusinessId());
                //Map<String,Object> content = new HashMap<>();
                //content.putAll(BeanUtils.objectToMap(bmsDxNews));
                /*if(StringUtils.isNotBlank(bmsDxNews.getContent()) && WebUtils.isJSONStr(bmsDxNews.getContent())){
                    content.putAll(JSON.parseObject(bmsDxNews.getContent()));
                    content.remove("content");
                }*/
                commonPushToDsxhAppDto.setContent(JSON.toJSONString(bmsDxNews));
                commonPushToDsxhAppDto.setDescribes("觅东东店铺");
                commonPushToDsxhAppDto.setTitle("觅东东通知");
                commonPushToDsxhAppDto.setType(Constants.MIDONGDONG_NEWS);
                MddDxshAppNewAdapterBo mddDxshAppNewAdapterBo = BmsDxNewsService.mddDxshAppNewAdapter(bmsDxNews);
                if(mddDxshAppNewAdapterBo == null){
                    log.info("推送失败. ");
                    return;
                }
                commonPushToDsxhAppDto.setDescribes(mddDxshAppNewAdapterBo.getDxshDescrible());
                commonPushToDsxhAppDto.setMainTitle(mddDxshAppNewAdapterBo.getMainTitle());
                commonPushToDsxhAppDto.setMessageType(mddDxshAppNewAdapterBo.getMessageType());
                commonPushToDsxhAppDto.setMessageSecondType(mddDxshAppNewAdapterBo.getMessageSecondType());

                /*if(bmsBusinessService != null) {
                    BmsBusiness bmsBusiness = bmsBusinessService.getBusinessById(bmsDxNews.getBmsBusinessId());
                    if(bmsBusiness != null && StringUtils.isNotBlank(bmsBusiness.getVendorName())){
                        commonPushToDsxhAppDto.setDescribes(bmsBusiness.getVendorName());
                    }
                }*/
                log.info("commonPushToDsxhAppDto:{}",JSON.toJSONString(commonPushToDsxhAppDto));
                dxshApiNewsRestService.commonPushToDxshApp_v2(commonPushToDsxhAppDto);
            }
        }
    }

    public static Pageable getPageable(Integer pageNum, Integer pageSize, Sort.Direction sort,String... orderField){
        if(pageNum < 1){
            pageNum = 1;
        }
        Pageable pageable = PageRequest.of(pageNum - 1,pageSize,sort,orderField);
        return pageable;
    }

    public static Pageable getPageable(Integer pageNum, Integer pageSize, Sort sort){
        if(pageNum < 1){
            pageNum = 1;
        }
        Pageable pageable = PageRequest.of(pageNum - 1,pageSize,sort);
        return pageable;
    }

    public static Pageable getPageable(Integer pageNum, Integer pageSize){
        if(pageNum < 1){
            pageNum = 1;
        }
        Pageable pageable = PageRequest.of(pageNum - 1,pageSize);
        return pageable;
    }

    public Map<String, Object> checkPhoneIsRegister(String phone) {
        BmsUser bmsUser = bmsUserService.getBaseDao().findByPhone(phone);
        //检测手机号是否存在
        if(bmsUser == null){
            return ResultMapHelper.result(ResultCode.CODE_USER_PHONE_NO_EXIST,"手机号不存在");
        }
        return ResultMapHelper.result(ResultCode.CODE_USER_PHONE_EXIST,"手机号已存在");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        BmsCommonService.applicationContext = applicationContext;
    }

    public Map<String,Object> saveUserLocation(ParamsMap paramsMap){
        String addrCity = paramsMap.getString("addrCity");
        String addrDistrict = paramsMap.getString("addrDistrict");
        String latitude = paramsMap.getString("latitude");
        String longitude = paramsMap.getString("longitude");
        String redisKey = Constants.REDIS_KEY_USER_LOCATION + paramsMap.getString("devId");
        String locData = String.format("%s:%s:%s:%s",addrCity,addrDistrict,longitude,latitude);
        RedisTemplateUtils.getRedisTemplate().opsForValue().set(redisKey,locData,1, TimeUnit.DAYS);
        return ResultMapHelper.success(null,"ok");
    }

    public static Logger getLogger(Class claess){
        return LoggerFactory.getLogger(claess);
    }

    public Map<String, Object> getServerData(ParamsMap paramsMap) {
        Map<String,Object> serverData = new HashMap<>();
        serverData.put("serverTime",new Date());
        return ResultMapHelper.success(serverData, ResultMsg.MSG_GET_SUCCESS);
    }

    public Map<String, Object> uploadImgFileEnhance(MultipartFile[] uploadFiles, Integer fileType) {
        //记录本地
        List<String> imgFileList = new LinkedList<>();
        //记录上传云的图片(用来删除)
        List<String> imgToCloud = new LinkedList<>();
        //记录图片上传原图
        List<Map<String,Object>> imgResultListInBig = new LinkedList<>();
        if(uploadFiles.length > 0){
            for(MultipartFile multipartFile : uploadFiles){
                if(multipartFile.isEmpty()){
                    return ResultMapHelper.failure("请上传相关图片文件");
                }
                if(!("image/jpeg".equals(multipartFile.getContentType()) || "image/png".equals(multipartFile.getContentType()))){
                    //清空之前上传的文件
                    return ResultMapHelper.failure("上传图片格式错误");
                }
            }
            for(MultipartFile multipartFile : uploadFiles){
                String uploadUrl = Upload.uploadImgFile(multipartFile,fileType);
                if("".equals(uploadUrl)){
                    deleteWasteFile(imgFileList);
                    deleteCloudFile(imgToCloud);
                    return ResultMapHelper.failure("文件上传失败");
                }
                imgFileList.add(uploadUrl);
                //上传到cdn文件服务器
                BmsCdnData bmsCdnData = this.uploadToCdnByEnhance(CDNUtils.bucketName,"/business/",uploadUrl);
                if(bmsCdnData == null){
                    deleteWasteFile(imgFileList);
                    deleteCloudFile(imgToCloud);
                    return ResultMapHelper.failure("文件上传失败");
                }
                Map<String,Object> imgMap = new LinkedHashMap<>();
                imgMap.put("big",bmsCdnData.getSourceUrlBig());
                imgMap.put("small",bmsCdnData.getSourceUrlSmall());
                imgResultListInBig.add(imgMap);
                //记录上传过的图片
                String[] bigUrls = bmsCdnData.getSourceUrlBig().split("/");
                String bigUrl = bigUrls[bigUrls.length - 1];
                imgToCloud.add(bigUrl);
                if(StringUtils.isNotBlank(bmsCdnData.getSourceUrlSmall())) {
                    String[] smallUrls = bmsCdnData.getSourceUrlSmall().split("/");
                    String smallUrl = smallUrls[smallUrls.length - 1];
                    imgToCloud.add(smallUrl);
                    String[] uploadRescover = uploadUrl.split("/");
                    List<String> rescover = new ArrayList<>();
                    for(int ii=0;ii< uploadRescover.length - 1;ii++){
                        rescover.add(uploadRescover[ii]);
                    }
                    imgFileList.add(StringUtils.join(rescover,"/") + "/" + smallUrl);
                }
            }
            if(imgFileList.size() > 0){
                deleteWasteFile(imgFileList);
                return ResultMapHelper.success(imgResultListInBig,"上传成功！");
            }
        }
        return ResultMapHelper.failure("请选择图片上传");

    }

    public List customPage(Integer pageNum, Integer pageSize, List list){
        Integer startIndex = (pageNum - 1) * pageSize;
        Integer endIndex = startIndex + pageSize;
        if(list.size() > startIndex) {
            if (endIndex > list.size()) {
                endIndex = list.size();
            }
            list = list.subList(startIndex, endIndex);
        }else {
            list = new LinkedList<>();
        }
        return list;
    }

    public Map<String, Object> uploadImgFileEnhance_v2(MultipartFile[] uploadFiles, Integer fileType) {
        //记录本地
        List<String> imgFileList = new LinkedList<>();
        //记录上传云的图片(用来删除)
        List<String> imgToCloud = new LinkedList<>();
        //记录图片上传原图
        List<Map<String,Object>> imgResultListInBig = new LinkedList<>();
        if(uploadFiles.length > 0){
            for(MultipartFile multipartFile : uploadFiles){
                if(multipartFile.isEmpty()){
                    return ResultMapHelper.failure("请上传相关图片文件");
                }
                if(!("image/jpeg".equals(multipartFile.getContentType()) || "image/png".equals(multipartFile.getContentType()))){
                    //清空之前上传的文件
                    return ResultMapHelper.failure("上传图片格式错误");
                }
            }
            for(MultipartFile multipartFile : uploadFiles){
                String uploadUrl = Upload.uploadImgFile(multipartFile,fileType);
                if("".equals(uploadUrl)){
                    deleteWasteFile(imgFileList);
                    deleteCloudFile(imgToCloud);
                    return ResultMapHelper.failure("文件上传失败");
                }
                imgFileList.add(uploadUrl);
                //上传到cdn文件服务器
                BmsCdnData bmsCdnData = this.uploadToCdnByEnhance(CDNUtils.bucketName,"/business/",uploadUrl);
                if(bmsCdnData == null){
                    deleteWasteFile(imgFileList);
                    deleteCloudFile(imgToCloud);
                    return ResultMapHelper.failure("文件上传失败");
                }
                Map<String,Object> imgMap = new LinkedHashMap<>();
                try {
                    URL bigUrl = new URL(bmsCdnData.getSourceUrlBig());
                    URL smallUrl = new URL(bmsCdnData.getSourceUrlSmall());
                    imgMap.put("big",bigUrl.getPath());
                    imgMap.put("small",smallUrl.getPath());
                } catch (MalformedURLException e) {
                   log.error(e.getMessage());
                    imgMap.put("big",bmsCdnData.getSourceUrlBig());
                    imgMap.put("small",bmsCdnData.getSourceUrlSmall());

                }

                imgResultListInBig.add(imgMap);
                //记录上传过的图片
                String[] bigUrls = bmsCdnData.getSourceUrlBig().split("/");
                String bigUrl = bigUrls[bigUrls.length - 1];
                imgToCloud.add(bigUrl);
                if(StringUtils.isNotBlank(bmsCdnData.getSourceUrlSmall())) {
                    String[] smallUrls = bmsCdnData.getSourceUrlSmall().split("/");
                    String smallUrl = smallUrls[smallUrls.length - 1];
                    imgToCloud.add(smallUrl);
                    String[] uploadRescover = uploadUrl.split("/");
                    List<String> rescover = new ArrayList<>();
                    for(int ii=0;ii< uploadRescover.length - 1;ii++){
                        rescover.add(uploadRescover[ii]);
                    }
                    imgFileList.add(StringUtils.join(rescover,"/") + "/" + smallUrl);
                }
            }
            if(imgFileList.size() > 0){
                deleteWasteFile(imgFileList);
                return ResultMapHelper.success(imgResultListInBig,"上传成功！");
            }
        }
        return ResultMapHelper.failure("请选择图片上传");
    }
}
